#!/bin/sh 
#
# $Id$
#
# use to check whether all ser processes are running; if not, restart
# and issue an alert; run from cron daemon for best results :-)
#


NOTIFY=sr@iptel.org
SERHOME=/home/srouter
export SERDIR=$SERHOME/sip_router
BIN=$SERDIR/ser
COREDIR=$SERHOME/core
CORE=$COREDIR/core
ETC=/etc/sr.cfg

PROCCNT=`ps -C sr --no-headers -o pid | wc -l`
CH=`grep "^children" $ETC | awk -F= ' { print $2 } '`
ALL=`expr $CH + 1`
TMP=/tmp/seralert.$$


if [ $PROCCNT -ne $ALL ] ; then 
	# try again first -- it might have been a temporary
	# failure during 'sr restart'

	# two seconds longer failure is not too bad...UAs will
	# just retransmit and user are used to longer call
	# set-up times from GSM...
	sleep 2 
	PROCCNT=`ps -C sr --no-headers -o pid | wc -l`
fi

if [ $PROCCNT -ne $ALL ] ; then 

	cd $SERDIR
	echo "Alarm: ser restart occurred on `date` at $HOSTNAME" > $TMP
	if [ -r $BIN -a -r $CORE ] ; then
		echo "----------------------------------" >> $TMP
		DATE=`date "+%Y-%m-%d--%H-%M"`
		NEWCORE=$COREDIR/core.$DATE
		mv $CORE $NEWCORE
		echo core stored in $NEWCORE >> $TMP
		gdb $BIN $NEWCORE -x test/bt.gdb -batch >> $TMP
		chmod a+r $NEWCORE
       ( cd $SERDIR; tar cf - . ) | gzip > $COREDIR/ser.$DATE.tgz

	else
		echo "no core found" >> $TMP
	fi

	/etc/init.d/sr restart
	mail -s "ser restart occurred" $NOTIFY < $TMP
	rm -f $TMP
fi
